import config
from lib.async_http import get
import asyncio
import server.gateway.main as gateway
import server.worker.main as worker
from typing import List


async def stop_server():
    await stop_gateway()
    await stop_worker()


async def stop_gateway():
    if config.Ver == "cross":
        return

    task_list: List[asyncio.Task] = []
    for gateway_url in await gateway.get_all_service():
        ip, port = gateway_url.split(":")
        url = f"http://{ip}:{port}/cmd/stop_server"
        task_list.append(asyncio.create_task(get(url)))
    await asyncio.gather(*task_list)


async def stop_worker():
    import socket

    for worker_url in await worker.get_all_service():
        ip, port = worker_url.split(":")
        _mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        _mySocket.connect((ip, int(port)))
        _mySocket.send(b'stop_server')
        _mySocket.close()


if __name__ == '__main__':
    import sys

    asyncio.run(stop_worker())
